import DataBus from '../databus'
import { SCREEN_WIDTH, SCREEN_HEIGHT } from '../render'

export default class Board {
  constructor() {
    this.databus = new DataBus()
    
    // 棋盘参数 - 适配竖屏
    this.boardRows = 10 // 10行
    this.boardCols = 9 // 9列
    this.cellSize = Math.min(SCREEN_WIDTH, SCREEN_HEIGHT) / 12 // 自适应格子大小
    this.boardPadding = 20 // 棋盘边距
    this.pieceRadius = this.cellSize * 0.4 // 棋子半径
    
    // 计算棋盘位置 - 居中显示，为控制面板留出空间
    this.boardWidth = (this.boardCols - 1) * this.cellSize
    this.boardHeight = (this.boardRows - 1) * this.cellSize
    this.startX = (SCREEN_WIDTH - this.boardWidth) / 2
    // 留出顶部空间给游戏信息，底部空间给控制面板
    this.startY = (SCREEN_HEIGHT - this.boardHeight) / 2 + 40 // 减少顶部空间，为控制面板留出空间
    
    // 确认状态 - 改为二次点击确认
    this.pendingMove = null
    this.previewMove = null // 预览落子
    this.selectedPiece = null // 当前选中的棋子
  }

  init() {
    this.databus.initBoard()
    this.pendingMove = null
    this.previewMove = null
  }

  update() {
    // 棋盘更新逻辑
  }

  render(ctx) {
    this.drawBoard(ctx)
    this.drawStones(ctx)
    this.drawPreviewMove(ctx) // 绘制预览落子
    this.drawLastMove(ctx)
  }

  drawBoard(ctx) {
    // 绘制棋盘背景
    ctx.fillStyle = '#DEB887'
    ctx.fillRect(this.startX - 10, this.startY - 10, this.boardWidth + 20, this.boardHeight + 20)
    
    // 绘制棋盘网格
    ctx.strokeStyle = '#8B4513'
    ctx.lineWidth = 2
    
    // 绘制横线（10条）
    for (let i = 0; i < this.boardRows; i++) {
      ctx.beginPath()
      ctx.moveTo(this.startX, this.startY + i * this.cellSize)
      ctx.lineTo(this.startX + this.boardWidth, this.startY + i * this.cellSize)
      ctx.stroke()
    }
    
    // 绘制竖线（9条）
    for (let i = 0; i < this.boardCols; i++) {
      ctx.beginPath()
      ctx.moveTo(this.startX + i * this.cellSize, this.startY)
      ctx.lineTo(this.startX + i * this.cellSize, this.startY + this.boardHeight)
      ctx.stroke()
    }
    
    // 绘制楚河汉界
    ctx.fillStyle = '#8B4513'
    ctx.font = `${this.cellSize * 0.3}px Arial`
    ctx.textAlign = 'center'
    ctx.fillText('楚河', this.startX + this.boardWidth / 4, this.startY + 4.5 * this.cellSize)
    ctx.fillText('汉界', this.startX + this.boardWidth * 3 / 4, this.startY + 4.5 * this.cellSize)
    
    // 绘制九宫格
    ctx.strokeStyle = '#8B4513'
    ctx.lineWidth = 3
    
    // 上方九宫格（黑方）
    ctx.beginPath()
    ctx.moveTo(this.startX + 3 * this.cellSize, this.startY)
    ctx.lineTo(this.startX + 5 * this.cellSize, this.startY)
    ctx.lineTo(this.startX + 5 * this.cellSize, this.startY + 2 * this.cellSize)
    ctx.lineTo(this.startX + 3 * this.cellSize, this.startY + 2 * this.cellSize)
    ctx.closePath()
    ctx.stroke()
    
    // 下方九宫格（红方）
    ctx.beginPath()
    ctx.moveTo(this.startX + 3 * this.cellSize, this.startY + 7 * this.cellSize)
    ctx.lineTo(this.startX + 5 * this.cellSize, this.startY + 7 * this.cellSize)
    ctx.lineTo(this.startX + 5 * this.cellSize, this.startY + 9 * this.cellSize)
    ctx.lineTo(this.startX + 3 * this.cellSize, this.startY + 9 * this.cellSize)
    ctx.closePath()
    ctx.stroke()
    
    // 绘制九宫格内的斜线
    ctx.lineWidth = 2
    
    // 上方九宫格斜线
    ctx.beginPath()
    ctx.moveTo(this.startX + 3 * this.cellSize, this.startY)
    ctx.lineTo(this.startX + 5 * this.cellSize, this.startY + 2 * this.cellSize)
    ctx.moveTo(this.startX + 5 * this.cellSize, this.startY)
    ctx.lineTo(this.startX + 3 * this.cellSize, this.startY + 2 * this.cellSize)
    ctx.stroke()
    
    // 下方九宫格斜线
    ctx.beginPath()
    ctx.moveTo(this.startX + 3 * this.cellSize, this.startY + 7 * this.cellSize)
    ctx.lineTo(this.startX + 5 * this.cellSize, this.startY + 9 * this.cellSize)
    ctx.moveTo(this.startX + 5 * this.cellSize, this.startY + 7 * this.cellSize)
    ctx.lineTo(this.startX + 3 * this.cellSize, this.startY + 9 * this.cellSize)
    ctx.stroke()
    
    // 绘制遮挡板遮住楚河汉界
    ctx.fillStyle = '#DEB887' // 使用与棋盘背景相同的颜色
    ctx.fillRect(
      this.startX - 10, 
      this.startY + 1 + 4* this.cellSize - this.cellSize * 0.05, 
      this.boardWidth + 20, 
      this.cellSize
    )
    
    // 绘制十字标记（兵卒和炮位）
    ctx.fillStyle = '#8B4513'
    ctx.lineWidth = 2
    
    // 炮位标记（第2行和第7行）
    const cannonPositions = [
      [2, 1], [2, 7], // 黑方炮位
      [7, 1], [7, 7]  // 红方炮位
    ]
    
    for (const [row, col] of cannonPositions) {
      const x = this.startX + col * this.cellSize
      const y = this.startY + row * this.cellSize
      
      // 绘制十字标记
      ctx.beginPath()
      ctx.moveTo(x - 4, y)
      ctx.lineTo(x + 4, y)
      ctx.moveTo(x, y - 4)
      ctx.lineTo(x, y + 4)
      ctx.stroke()
    }
    
    // 兵卒位标记（第3行和第6行）
    const soldierPositions = [
      [3, 0], [3, 2], [3, 4], [3, 6], [3, 8], // 黑方兵位
      [6, 0], [6, 2], [6, 4], [6, 6], [6, 8]  // 红方兵位
    ]
    
    for (const [row, col] of soldierPositions) {
      const x = this.startX + col * this.cellSize
      const y = this.startY + row * this.cellSize
      
      // 绘制十字标记
      ctx.beginPath()
      ctx.moveTo(x - 4, y)
      ctx.lineTo(x + 4, y)
      ctx.moveTo(x, y - 4)
      ctx.lineTo(x, y + 4)
      ctx.stroke()
    }
  }

  drawStones(ctx) {
    for (let i = 0; i < this.boardRows; i++) {
      for (let j = 0; j < this.boardCols; j++) {
        if (this.databus.board[i][j] && this.databus.board[i][j] !== 0) {
          const piece = this.databus.board[i][j]
          const x = this.startX + j * this.cellSize
          const y = this.startY + i * this.cellSize
          
          // 绘制棋子阴影
          ctx.fillStyle = 'rgba(0, 0, 0, 0.3)'
          ctx.beginPath()
          ctx.arc(x + 2, y + 2, this.pieceRadius, 0, 2 * Math.PI)
          ctx.fill()
          
          // 绘制棋子背景
          if (piece.player === 1) {
            // 红方棋子
            const gradient = ctx.createRadialGradient(x - 5, y - 5, 0, x, y, this.pieceRadius)
            gradient.addColorStop(0, '#ffcccc')
            gradient.addColorStop(1, '#cc0000')
            ctx.fillStyle = gradient
          } else {
            // 黑方棋子
            const gradient = ctx.createRadialGradient(x - 5, y - 5, 0, x, y, this.pieceRadius)
            gradient.addColorStop(0, '#666666')
            gradient.addColorStop(1, '#000000')
            ctx.fillStyle = gradient
          }
          
          ctx.beginPath()
          ctx.arc(x, y, this.pieceRadius, 0, 2 * Math.PI)
          ctx.fill()
          
          // 绘制棋子边框
          ctx.strokeStyle = piece.player === 1 ? '#cc0000' : '#000000'
          ctx.lineWidth = 2
          ctx.stroke()
          
          // 绘制棋子文字
          ctx.fillStyle = '#ffffff'
          ctx.font = `${this.cellSize * 0.4}px Arial`
          ctx.textAlign = 'center'
          ctx.textBaseline = 'middle'
          
          const pieceText = this.getPieceText(piece.type, piece.player)
          ctx.fillText(pieceText, x, y)
        }
      }
    }
  }
  
  getPieceText(type, player) {
    const pieceMap = {
      'jiang': player === 1 ? '帅' : '将',
      'shi': '士',
      'xiang': player === 1 ? '相' : '象',
      'ma': '马',
      'che': '车',
      'pao': '炮',
      'bing': player === 1 ? '兵' : '卒'
    }
    return pieceMap[type] || '?'
  }

  drawPreviewMove(ctx) {
    // 绘制选中的棋子高亮
    if (this.selectedPiece) {
      const x = this.startX + this.selectedPiece.col * this.cellSize
      const y = this.startY + this.selectedPiece.row * this.cellSize
      
      // 绘制选中棋子的高亮边框
      ctx.strokeStyle = '#00FF00'
      ctx.lineWidth = 3
      ctx.beginPath()
      ctx.arc(x, y, this.pieceRadius + 5, 0, 2 * Math.PI)
      ctx.stroke()
      
      // 绘制闪烁效果
      ctx.globalAlpha = 0.3 + 0.3 * Math.sin(Date.now() * 0.01)
      ctx.strokeStyle = '#00FF00'
      ctx.lineWidth = 2
      ctx.beginPath()
      ctx.arc(x, y, this.pieceRadius + 8, 0, 2 * Math.PI)
      ctx.stroke()
      
      // 恢复透明度
      ctx.globalAlpha = 1.0
    }
  }

  drawLastMove(ctx) {
    if (this.databus.lastMove) {
      const x = this.startX + this.databus.lastMove.col * this.cellSize
      const y = this.startY + this.databus.lastMove.row * this.cellSize
      
      // 绘制最后一步的标记
      ctx.strokeStyle = '#FF0000'
      ctx.lineWidth = 3
      ctx.beginPath()
      ctx.arc(x, y, this.pieceRadius + 3, 0, 2 * Math.PI)
      ctx.stroke()
    }
  }

  handleTouch(x, y) {
    // 检查是否点击在棋盘范围内 - 放宽边界检查
    const margin = this.cellSize * 0.3 // 允许一定的点击容差
    if (x < this.startX - margin || x > this.startX + this.boardWidth + margin ||
        y < this.startY - margin || y > this.startY + this.boardHeight + margin) {
      console.log('点击位置超出棋盘范围:', { x, y, startX: this.startX, startY: this.startY, boardWidth: this.boardWidth, boardHeight: this.boardHeight })
      return null
    }
    
    // 计算点击的格子位置
    let col = Math.round((x - this.startX) / this.cellSize)
    let row = Math.round((y - this.startY) / this.cellSize)
    
    // 边界修正
    if (col >= this.boardCols) col = this.boardCols - 1
    if (row >= this.boardRows) row = this.boardRows - 1
    if (col < 0) col = 0
    if (row < 0) row = 0
    
    console.log('坐标计算:', { 
      x, y, 
      startX: this.startX, startY: this.startY, 
      cellSize: this.cellSize,
      rawCol: Math.round((x - this.startX) / this.cellSize),
      rawRow: Math.round((y - this.startY) / this.cellSize),
      adjustedCol: col,
      adjustedRow: row,
      boardRows: this.boardRows,
      boardCols: this.boardCols
    })
    
    // 检查位置是否有效
    if (row < 0 || row >= this.boardRows || col < 0 || col >= this.boardCols) {
      console.log('点击位置超出棋盘范围:', { x, y, row, col, boardRows: this.boardRows, boardCols: this.boardCols })
      return null
    }
    
    // 象棋移动逻辑：选择棋子或移动棋子
    const clickedPiece = this.databus.board[row][col]
    
    if (clickedPiece && clickedPiece.player === this.databus.currentPlayer) {
      // 点击了自己的棋子，选择该棋子
      this.selectedPiece = { row, col, piece: clickedPiece }
      console.log('选择了棋子:', { row, col, piece: clickedPiece })
      return null
    } else if (this.selectedPiece) {
      // 已经选择了棋子，尝试移动
      const fromRow = this.selectedPiece.row
      const fromCol = this.selectedPiece.col
      const piece = this.selectedPiece.piece
      
      // 检查移动是否合法
      if (this.databus.isValidMove(fromRow, fromCol, row, col, this.databus.currentPlayer)) {
        // 记录被吃的棋子
        const capturedPiece = this.databus.board[row][col]
        
        // 执行移动
        this.databus.board[row][col] = piece
        this.databus.board[fromRow][fromCol] = 0
        
        // 记录移动历史
        this.databus.recordMove(fromRow, fromCol, row, col, this.databus.currentPlayer, capturedPiece)
        
        // 检查是否获胜
        if (this.databus.checkWin(row, col, this.databus.currentPlayer)) {
          this.databus.setGameOver(this.databus.currentPlayer)
          console.log('游戏结束，获胜者:', this.databus.currentPlayer)
        } else if (this.databus.checkDraw()) {
          this.databus.setGameOver(0) // 和棋
          console.log('游戏结束，和棋')
        } else {
          // 切换玩家
          this.databus.switchPlayer()
        }
        
        // 清除选择状态
        this.selectedPiece = null
        console.log('移动完成:', { fromRow, fromCol, toRow: row, toCol: col, piece })
        return { moved: true, fromRow, fromCol, toRow: row, toCol: col, piece }
      } else {
        console.log('移动不合法:', { fromRow, fromCol, toRow: row, toCol: col, piece })
        // 如果点击的是其他位置，清除选择
        this.selectedPiece = null
        return null
      }
    } else {
      console.log('点击了空位置或对方棋子')
      return null
    }
  }

  confirmMove() {
    if (!this.pendingMove) {
      console.warn('confirmMove called but no pending move')
      return
    }
    
    const { row, col, player } = this.pendingMove
    
    if (row === undefined || col === undefined || player === undefined) {
      console.error('Invalid pending move:', this.pendingMove)
      this.pendingMove = null
      return
    }
    
    // 落子
    this.databus.board[row][col] = player
    this.databus.lastMove = { row, col }
    // 注意：这个recordMove调用参数不正确，但在象棋中confirmMove不会被使用
    // this.databus.recordMove(row, col, player)
    
    // 检查是否获胜
    if (this.databus.checkWin(row, col, player)) {
      this.databus.winner = player
      this.databus.gameOver = true
    } else {
      // 检查是否平局
      if (this.databus.checkDraw()) {
        this.databus.winner = 0 // 0表示平局
        this.databus.gameOver = true
      } else {
        // 切换玩家
        this.databus.switchPlayer()
        
        // 在线模式下更新回合状态
        if (this.databus.isOnlineMode) {
          this.databus.isMyTurn = this.databus.currentPlayer === this.databus.myStoneColor
        }
        
        // AI模式下，如果轮到AI，则AI自动落子
        if (this.databus.isAIMode && this.databus.currentPlayer === this.databus.aiPlayer) {
          // 延迟一小段时间，让玩家看到落子效果
          setTimeout(() => {
            this.makeAIMove()
          }, 500)
        }
      }
    }
    
    this.pendingMove = null
  }

  /**
   * AI自动落子
   */
  makeAIMove() {
    if (this.databus.gameOver) return
    
    // 获取AI实例（兼容不同环境）
    let gameAI = null
    if (typeof window !== 'undefined' && window.gameAI) {
      gameAI = window.gameAI
    } else if (typeof GameGlobal !== 'undefined' && GameGlobal.gameAI) {
      gameAI = GameGlobal.gameAI
    }
    
    if (!gameAI) {
      console.error('AI实例未找到')
      return
    }
    
    // 记录AI开始思考时间
    const startTime = Date.now()
    
    // 获取AI的下一步移动
    const aiMove = gameAI.getNextMove(this.databus.board, this.databus.currentPlayer)
    
    // 记录AI思考结束时间
    const endTime = Date.now()
    
    if (aiMove && aiMove.fromRow !== undefined && aiMove.fromCol !== undefined && 
        aiMove.toRow !== undefined && aiMove.toCol !== undefined) {
      
      // 记录被吃的棋子
      const capturedPiece = this.databus.board[aiMove.toRow][aiMove.toCol]
      
      // 执行AI移动
      this.databus.board[aiMove.toRow][aiMove.toCol] = this.databus.board[aiMove.fromRow][aiMove.fromCol]
      this.databus.board[aiMove.fromRow][aiMove.fromCol] = 0
      
      // 记录移动历史
      this.databus.recordMove(aiMove.fromRow, aiMove.fromCol, aiMove.toRow, aiMove.toCol, this.databus.currentPlayer, capturedPiece)
      
      // 检查是否获胜
      if (this.databus.checkWin(aiMove.toRow, aiMove.toCol, this.databus.currentPlayer)) {
        this.databus.setGameOver(this.databus.currentPlayer)
      } else if (this.databus.checkDraw()) {
        this.databus.setGameOver(0) // 和棋
      } else {
        // 切换回玩家
        this.databus.switchPlayer()
      }
    }
  }

  setPendingMove(move) {
    if (move && move.row !== undefined && move.col !== undefined && move.player !== undefined) {
      this.pendingMove = move
    } else {
      console.error('Invalid move data:', move)
      this.pendingMove = null
    }
  }

  clearPreview() {
    this.previewMove = null
    this.pendingMove = null
  }
} 